IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[cms_sp_Content_Save]') AND type in (N'P', N'PC'))
	DROP PROCEDURE [dbo].[cms_sp_Content_Save]
GO
create procedure [dbo].[cms_sp_Content_Save]
(
	@Id int output,	
	@SiteGroupId int = null,
	@SiteId int = null,
	@ContentTypeId int,
	@SystemLanguageId int = null,
	@ContentTitle nvarchar(250),
	@ContentSummary nvarchar(500) = null,
	@ContentBody nvarchar(max) = null,
	@ContentCode nvarchar(150) = null,
	@CreatedBy int,
	@DateCreated datetime,
	@LastUpdatedBy int = null,
	@DateLastUpdated datetime = null,
	@IsPublished bit = 1,
	@PublishEndDate datetime = null, 
	@PublishStartDate datetime = null
)
as
begin
declare @pid int
select top 1 @pid = c.PublicContentId from Contents c where c.ContentId=@Id
declare @type nvarchar(100)
set @type = 'Content' + CAST(@ContentTypeId as nvarchar(50))
if exists(select * from ContentTypes where ContentTypeId = @ContentTypeId and IsSupportedRevisions = 1)
begin
	insert into dbo.Contents
	(
		SiteGroupId,
		SiteId,
		SystemLanguageId,
		ContentTypeId,
		ContentTitle,
		ContentSummary,
		ContentBody,
		CreatedBy,
		DateCreated,
		PublicContentId
	)
	values
	(
		@SiteGroupId,
		@SiteId,
		@SystemLanguageId,
		@ContentTypeId,
		@ContentTitle,
		@ContentSummary,
		@ContentBody,
		@CreatedBy,
		@DateCreated,
		@pid
	)
	set @Id = SCOPE_IDENTITY()
	-- while there is no workflow reset previous flags and set news
	update EntityRevisions
	set IsLatestCompletedRevision = 0, IsLatestRevision = 0
	where PublicEntityId=@pid and EntityTypeParameter = @type
	INSERT INTO [dbo].[EntityRevisions]
           ([EntityId]
           ,[EntityTypeParameter]
           ,[IsLatestRevision]
           ,[IsLatestCompletedRevision]
           ,[IsDeleted]
           ,[WorkflowId]
           ,[PublishStartDate]
           ,[PublishEndDate]
           ,[IsPublished]
           ,[PublicEntityId])
     VALUES
           (@Id
           ,@type
           ,1
           ,1
           ,0
           ,null
           ,@PublishStartDate
           ,@PublishEndDate
           ,@IsPublished
           ,@pid)
end
else
begin
	update dbo.Contents
	set
		SiteGroupId = @SiteGroupId,
		SiteId = @SiteId,
		SystemLanguageId = @SystemLanguageId,
		ContentTypeId = @ContentTypeId,
		ContentTitle = @ContentTitle,
		ContentSummary = @ContentSummary,
		ContentBody = @ContentBody,
		CreatedBy = @CreatedBy,
		DateCreated = @DateCreated
	where ContentId = @Id
	update EntityRevisions
	set [PublishStartDate] = @PublishStartDate,
		[PublishEndDate] = @PublishEndDate,
		[IsPublished] = @IsPublished
	where PublicEntityId=@pid and EntityTypeParameter = @type
end

return @Id

end


GO

